package fr.univ.lille1.server.webservice;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import fr.univ.lille1.server.domain.SessionKey;
import fr.univ.lille1.server.domain.User;
import fr.univ.lille1.server.manager.SessionKeyManager;
import fr.univ.lille1.server.manager.UserManager;

@Path("/")
@Stateless
@LocalBean
@Produces("application/json")
public class SessionLocalWebService {

	@EJB
	private UserManager userManager;

	@EJB
	private SessionKeyManager sessionKeyManager;


	@POST
	@Path("/login")
	public SessionKey login(@FormParam("mail") String mail, @FormParam("password") String password) {
		boolean logged = userManager.login(mail, password);
		if(!logged) {
			System.out.println("coucou");
			return null;
		}

		User u = userManager.findUserByMail(mail);
		SessionKey sessionKey= sessionKeyManager.findSessionKeyByUserId(u.getId());
		if(sessionKey==null){
			sessionKeyManager.createSessionKey(u, "",0);
		}
		return sessionKeyManager.generateNewKey(u);
		
	}


	@POST
	@Path("/logout")
	public void logout(@FormParam("login") String mail){
		User u = userManager.findUserByMail(mail);
		SessionKey sessionKey = sessionKeyManager.findSessionKeyByUserId(u.getId());
		sessionKey.setSessionKey("");
		sessionKey.setGenerateTime(0);
		sessionKeyManager.updateSessionKey(sessionKey);
	}
               
}